# -*- coding: utf-8 -*-

import os, hashlib
from django.db import models
from core.models import CoreModel, table_prefix

"""鹰眼对象"""


class Hawkeye(CoreModel):
    host = models.ForeignKey(
        to="oms.Host",
        related_name="hawkeye_set",
        on_delete=models.DO_NOTHING,
        db_constraint=False,
        verbose_name="主机信息",
    )
    title = models.CharField(null=True, blank=True, max_length=128, verbose_name="主题")
    message = models.TextField(verbose_name="监控日志")
    analysis = models.CharField(
        null=True, blank=True, max_length=50, verbose_name="分析结论"
    )

    def __str__(self) -> str:
        return "%s(%s)" % (self.host.address, self.message)

    class Meta:
        db_table = table_prefix + "oms_hawkeye"
        verbose_name = "鹰眼监控"
        verbose_name_plural = verbose_name
        ordering = ("-create_time",)


class HawkeyeJob(CoreModel):
    """鹰眼任务管理"""

    name = models.CharField(
        max_length=128, null=True, blank=True, verbose_name="任务名称"
    )
    hosts = models.ManyToManyField(
        blank=True,
        to="oms.Host",
        related_name="hawkeye_job_set",
        db_constraint=False,
        verbose_name="主机名称",
    )
    plugin = models.ForeignKey(
        null=True,
        blank=True,
        to="HawkeyeJobPlugin",
        related_name="hawkeye_job_set",
        on_delete=models.DO_NOTHING,
        db_constraint=False,
        verbose_name="执行插件",
    )
    cron = models.CharField(
        max_length=256, null=True, blank=True, verbose_name="cron表达式"
    )
    detail = models.TextField(null=True, blank=True, verbose_name="详细日志")

    def __str__(self) -> str:
        return self.name

    class Meta:
        db_table = table_prefix + "oms_hawkeye_job"
        verbose_name = "鹰眼任务管理"
        verbose_name_plural = verbose_name
        ordering = ("-create_time",)


def media_file_name(instance, filename):
    h = instance.md5sum
    basename, ext = os.path.splitext(filename)
    return os.path.join("hawkeye/plugins", h[0:1], h[1:2], h + ext.lower())


class HawkeyeJobPlugin(CoreModel):
    """任务插件"""

    name = models.CharField(null=True, blank=True, max_length=50, verbose_name="名称")
    file = models.FileField(upload_to=media_file_name)
    size = models.IntegerField(default=0, verbose_name="文件大小")
    md5sum = models.CharField(blank=True, max_length=36, verbose_name="文件md5")

    def __str__(self) -> str:
        return self.file.url

    def save(self, *args, **kwargs):
        if not self.md5sum:  # file is new
            md5 = hashlib.md5()
            for chunk in self.file.chunks():
                md5.update(chunk)
            self.md5sum = md5.hexdigest()
        super(HawkeyeJobPlugin, self).save(*args, **kwargs)

    class Meta:
        db_table = table_prefix + "oms_hawkeye_job_plugin"
        verbose_name = "鹰眼任务插件"
        verbose_name_plural = verbose_name
        ordering = ("-create_time",)
